<template>
  <div class="user-center-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <h1>个人中心</h1>
      <p>管理个人信息和学习数据</p>
    </div>
    
    <!-- 用户信息头部 -->
    <UserHeader :userInfo="userInfo" :userStats="userStats" />
    
    <!-- 主要内容区域 -->
    <div class="user-center-content">
      <el-tabs v-model="activeTab" class="user-tabs">
        <!-- 学习记录标签页 -->
        <el-tab-pane label="我的课程" name="learning">
          <LearningRecords 
            :learningRecords="learningRecords" 
            :favoriteCourses="favoriteCourses" 
            @remove-favorite="removeFavorite"
          />
        </el-tab-pane>
        
        <!-- 我的收藏标签页 -->
        <el-tab-pane label="我的收藏" name="favorites">
          <UserFavorites 
            :favoriteDiscussions="favoriteDiscussions"
            :favoriteQuestions="favoriteQuestions"
            :favoriteNotes="favoriteNotes"
            @remove-favorite-discussion="removeFavoriteDiscussion"
            @remove-favorite-question="removeFavoriteQuestion"
            @remove-favorite-note="removeFavoriteNote"
          />
        </el-tab-pane>
        
        <!-- 我的内容标签页 -->
        <el-tab-pane label="我的内容" name="content">
          <UserContent 
            :userDiscussions="userDiscussions"
            :userQuestions="userQuestions"
            :userNotes="userNotes"
            @edit-discussion="editDiscussion"
            @delete-discussion="deleteDiscussion"
            @edit-question="editQuestion"
            @delete-question="deleteQuestion"
            @edit-note="editNote"
            @delete-note="deleteNote"
          />
        </el-tab-pane>
        
        <!-- 订单记录标签页 -->
        <el-tab-pane label="订单记录" name="orders">
          <OrderRecords 
            :orderRecords="orderRecords"
            @view-order="viewOrder"
            @pay-order="payOrder"
          />
        </el-tab-pane>
        
        <!-- 账号设置标签页 -->
        <el-tab-pane label="账号设置" name="settings">
          <AccountSettings 
            :userInfo="userInfo"
            @update-user-info="updateUserInfo"
          />
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
// 导入Vue核心功能
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';

// 导入Element Plus图标
import {
  View,
  ChatDotRound,
  Star,
  Plus,
  Upload
} from '@element-plus/icons-vue';

// 导入子组件
import UserHeader from '@/components/user/UserHeader.vue';
import LearningRecords from '@/components/user/LearningRecords.vue';
import UserFavorites from '@/components/user/UserFavorites.vue';
import UserContent from '@/components/user/UserContent.vue';
import OrderRecords from '@/components/user/OrderRecords.vue';
import AccountSettings from '@/components/user/AccountSettings.vue';

const router = useRouter();

// 标签页状态
const activeTab = ref('learning'); // 默认选中学习记录标签页
const learningSubTab = ref('recent');
const favoritesSubTab = ref('discussions');
const contentSubTab = ref('discussions');

// 注意：以下对话框状态已移至AccountSettings组件中，这里保留注释以便了解整体结构
// 对话框状态
// const changePasswordDialogVisible = ref(false);
// const bindPhoneDialogVisible = ref(false);
// const deleteAccountDialogVisible = ref(false);

// 验证码按钮状态
// const codeButtonDisabled = ref(false);
// const codeButtonText = ref('获取验证码');
// let countdownTimer = null;

// 用户基本信息
const userInfo = reactive({
  id: 1,
  username: 'student001',
  nickname: '学习达人',
  email: 'student001@example.com',
  phone: '13800138000',
  avatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
  school: '示例中学',
  grade: '高二',
  bio: '热爱学习，热爱生活'
});

// 用户统计数据
const userStats = reactive({
  studyDays: 120,
  completedTasks: 85,
  averageScore: 92,
  totalStudyTime: 12600, // 秒
  mistakesCount: 45
});

// 注意：以下表单数据和验证规则已移至AccountSettings组件中，这里保留注释以便了解整体结构
// 表单数据
// const userForm = reactive({
//   username: userInfo.username,
//   nickname: userInfo.nickname,
//   email: userInfo.email,
//   phone: userInfo.phone,
//   avatar: userInfo.avatar,
//   school: userInfo.school,
//   grade: userInfo.grade,
//   bio: userInfo.bio
// });

// const passwordForm = reactive({
//   currentPassword: '',
//   newPassword: '',
//   confirmPassword: ''
// });

// const phoneForm = reactive({
//   phone: '',
//   verificationCode: ''
// });

// const deleteAccountForm = reactive({
//   password: '',
//   confirm: false
// });

// 表单验证规则
// const userRules = {
//   nickname: [
//     { required: true, message: '请输入昵称', trigger: 'blur' },
//     { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
//   ],
//   email: [
//     { required: true, message: '请输入邮箱地址', trigger: 'blur' },
//     { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
//   ],
//   school: [
//     { max: 50, message: '长度不能超过 50 个字符', trigger: 'blur' }
//   ],
//   bio: [
//     { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
//   ]
// };

// const passwordRules = {
//   currentPassword: [
//     { required: true, message: '请输入当前密码', trigger: 'blur' }
//   ],
//   newPassword: [
//     { required: true, message: '请输入新密码', trigger: 'blur' },
//     { min: 6, message: '密码长度不能小于 6 个字符', trigger: 'blur' }
//   ],
//   confirmPassword: [
//     { required: true, message: '请确认密码', trigger: 'blur' },
//     { 
//       validator: (rule, value, callback) => {
//         if (value !== passwordForm.newPassword) {
//           callback(new Error('两次输入密码不一致'));
//         } else {
//           callback();
//         }
//       }, 
//       trigger: 'blur' 
//     }
//   ]
// };

// const phoneRules = {
//   phone: [
//     { required: true, message: '请输入手机号码', trigger: 'blur' },
//     { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
//   ],
//   verificationCode: [
//     { required: true, message: '请输入验证码', trigger: 'blur' },
//     { len: 6, message: '验证码长度应为 6 位', trigger: 'blur' }
//   ]
// };

// const deleteAccountRules = {
//   password: [
//     { required: true, message: '请输入密码', trigger: 'blur' }
//   ],
//   confirm: [
//     { 
//       validator: (rule, value, callback) => {
//         if (!value) {
//           callback(new Error('请确认注销账号'));
//         } else {
//           callback();
//         }
//       }, 
//       trigger: 'change' 
//     }
//   ]
// };

// 引用
// const userFormRef = ref(null);
// const passwordFormRef = ref(null);
// const phoneFormRef = ref(null);
// const deleteAccountFormRef = ref(null);

// 模拟数据
const learningRecords = ref([
  {
    id: 1,
    title: '高中数学必修一',
    subject: '数学',
    progress: 75,
    lastStudyTime: '2023-05-15',
    studyDuration: 45,
    image: 'https://picsum.photos/id/1/350/150'
  },
  {
    id: 2,
    title: '高中物理必修二',
    subject: '物理',
    progress: 60,
    lastStudyTime: '2023-05-14',
    studyDuration: 30,
    image: 'https://picsum.photos/id/2/350/150'
  },
  {
    id: 3,
    title: '高中化学选修一',
    subject: '化学',
    progress: 90,
    lastStudyTime: '2023-05-13',
    studyDuration: 60,
    image: 'https://picsum.photos/id/3/350/150'
  }
]);

const favoriteCourses = ref([
  {
    id: 1,
    title: '高中数学竞赛技巧',
    subject: '数学',
    teacher: '张老师',
    studentsCount: 1200,
    price: 199,
    originalPrice: 299,
    image: 'https://picsum.photos/id/4/350/150'
  },
  {
    id: 2,
    title: '高考物理冲刺班',
    subject: '物理',
    teacher: '李老师',
    studentsCount: 980,
    price: 299,
    originalPrice: 399,
    image: 'https://picsum.photos/id/5/350/150'
  }
]);

const favoriteDiscussions = ref([
  {
    id: 1,
    title: '如何高效学习数学？',
    content: '数学学习需要理解概念，多做练习，掌握解题技巧。我想知道大家有什么好的学习方法可以分享...',
    author: '数学爱好者',
    createdAt: '2023-05-10',
    views: 1200,
    comments: 45,
    favorites: 78
  },
  {
    id: 2,
    title: '物理实验的注意事项',
    content: '做物理实验时需要注意安全，准确记录数据，认真分析结果。我在做力学实验时遇到了一些问题...',
    author: '物理研究者',
    createdAt: '2023-05-08',
    views: 980,
    comments: 32,
    favorites: 56
  }
]);

const favoriteQuestions = ref([
  {
    id: 1,
    title: '如何解决这道数学题？',
    content: '已知函数f(x)=x²+ax+b在点(1,2)处取得极值，且f(0)=1，求a和b的值...',
    author: '数学学习者',
    createdAt: '2023-05-12',
    views: 850,
    answers: 15,
    favorites: 42
  },
  {
    id: 2,
    title: '化学平衡常数的计算问题',
    content: '在一定条件下，反应A+B⇌C+D的平衡常数K=2，已知平衡时[A]=0.5mol/L，[B]=0.3mol/L，求[C]和[D]的值...',
    author: '化学爱好者',
    createdAt: '2023-05-09',
    views: 720,
    answers: 8,
    favorites: 35
  }
]);

const favoriteNotes = ref([
  {
    id: 1,
    title: '数学函数知识点总结',
    content: '函数是描述两个变量之间对应关系的数学概念。常见的函数类型包括线性函数、二次函数、指数函数、对数函数等...',
    author: '数学笔记达人',
    createdAt: '2023-05-11',
    views: 980,
    likes: 65,
    favorites: 48
  },
  {
    id: 2,
    title: '物理力学知识点整理',
    content: '力学是研究物体运动规律的物理学分支。牛顿三大定律是经典力学的基础：惯性定律、加速度定律和作用力与反作用力定律...',
    author: '物理学习者',
    createdAt: '2023-05-07',
    views: 850,
    likes: 52,
    favorites: 39
  }
]);

const userDiscussions = ref([
  {
    id: 1,
    title: '分享我的学习方法',
    content: '我在学习过程中总结了一些高效的学习方法，包括番茄工作法、思维导图、间隔重复等，希望对大家有所帮助...',
    createdAt: '2023-05-14',
    views: 560,
    comments: 28,
    favorites: 45
  }
]);

const userQuestions = ref([
  {
    id: 1,
    title: '求解这道物理题',
    content: '一个质量为m的物体从高度h处自由落下，落到地面后反弹到高度h/2，求反弹过程中物体的动能损失...',
    createdAt: '2023-05-13',
    views: 320,
    answers: 5,
    favorites: 12
  }
]);

const userNotes = ref([
  {
    id: 1,
    title: '英语语法笔记',
    content: '英语时态包括一般现在时、一般过去时、一般将来时、现在进行时、过去进行时、将来进行时、现在完成时等...',
    createdAt: '2023-05-15',
    views: 230,
    likes: 18,
    favorites: 15
  }
]);

const orderRecords = ref([
  {
    id: 1,
    orderNo: '202305150001',
    createTime: '2023-05-15 10:30:45',
    amount: 299,
    status: 'completed',
    course: {
      id: 1,
      name: '高考数学冲刺班',
      image: 'https://picsum.photos/id/6/60/40'
    }
  },
  {
    id: 2,
    orderNo: '202305100002',
    createTime: '2023-05-10 15:20:30',
    amount: 199,
    status: 'completed',
    course: {
      id: 2,
      name: '高中物理专题课程',
      image: 'https://picsum.photos/id/7/60/40'
    }
  }
]);

// 方法：格式化时间
const formatTime = (seconds) => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  return `${hours}小时${minutes}分钟`;
};

// 方法：继续学习
const continueLearning = (record) => {
  router.push(`/course/${record.id}`);
};

// 方法：查看学习记录
const viewLearningRecord = (record) => {
  router.push(`/course/${record.id}/detail`);
};

// 方法：查看课程
const viewCourse = (course) => {
  router.push(`/course/${course.id}`);
};

// 方法：取消收藏课程
const removeFavorite = (course) => {
  const index = favoriteCourses.value.findIndex(c => c.id === course.id);
  if (index !== -1) {
    favoriteCourses.value.splice(index, 1);
    ElMessage.success('已取消收藏');
  }
};

// 方法：查看讨论
const viewDiscussion = (discussion) => {
  router.push(`/community/discussion/${discussion.id}`);
};

// 方法：取消收藏讨论
const removeFavoriteDiscussion = (discussion) => {
  const index = favoriteDiscussions.value.findIndex(d => d.id === discussion.id);
  if (index !== -1) {
    favoriteDiscussions.value.splice(index, 1);
    ElMessage.success('已取消收藏');
  }
};

// 方法：查看问题
const viewQuestion = (question) => {
  router.push(`/community/question/${question.id}`);
};

// 方法：取消收藏问题
const removeFavoriteQuestion = (question) => {
  const index = favoriteQuestions.value.findIndex(q => q.id === question.id);
  if (index !== -1) {
    favoriteQuestions.value.splice(index, 1);
    ElMessage.success('已取消收藏');
  }
};

// 方法：查看笔记
const viewNote = (note) => {
  router.push(`/notes/${note.id}`);
};

// 方法：取消收藏笔记
const removeFavoriteNote = (note) => {
  const index = favoriteNotes.value.findIndex(n => n.id === note.id);
  if (index !== -1) {
    favoriteNotes.value.splice(index, 1);
    ElMessage.success('已取消收藏');
  }
};

// 方法：更新用户信息
const updateUserInfo = () => {
  userFormRef.value.validate((valid) => {
    if (valid) {
      // 更新用户信息
      Object.assign(userInfo, userForm);
      ElMessage.success('个人信息已更新');
    } else {
      return false;
    }
  });
};

// 方法：重置表单
const resetForm = () => {
  userFormRef.value.resetFields();
};

// 注意：以下方法已移至AccountSettings组件中，这里保留注释以便了解整体结构
// 方法：显示修改密码对话框
// const showChangePasswordDialog = () => {
//   passwordForm.currentPassword = '';
//   passwordForm.newPassword = '';
//   passwordForm.confirmPassword = '';
//   changePasswordDialogVisible.value = true;
// };

// 方法：修改密码
// const changePassword = () => {
//   passwordFormRef.value.validate((valid) => {
//     if (valid) {
//       // 这里应该调用API修改密码
//       ElMessage.success('密码修改成功');
//       changePasswordDialogVisible.value = false;
//     } else {
//       return false;
//     }
//   });
// };

// 方法：显示绑定手机对话框
// const showBindPhoneDialog = () => {
//   phoneForm.phone = userInfo.phone || '';
//   phoneForm.verificationCode = '';
//   bindPhoneDialogVisible.value = true;
// };

// 方法：发送验证码
// const sendVerificationCode = () => {
//   phoneFormRef.value.validateField('phone', (valid) => {
//     if (!valid) {
//       // 开始倒计时
//       codeButtonDisabled.value = true;
//       let countdown = 60;
//       codeButtonText.value = `${countdown}秒后重新获取`;
//       
//       countdownTimer = setInterval(() => {
//         countdown--;
//         codeButtonText.value = `${countdown}秒后重新获取`;
//         if (countdown <= 0) {
//           clearInterval(countdownTimer);
//           codeButtonDisabled.value = false;
//           codeButtonText.value = '获取验证码';
//         }
//       }, 1000);
//       
//       // 这里应该调用API发送验证码
//       ElMessage.success('验证码已发送');
//     }
//   });
// };

// 方法：绑定手机
// const bindPhone = () => {
//   phoneFormRef.value.validate((valid) => {
//     if (valid) {
//       // 这里应该调用API绑定手机
//       userInfo.phone = phoneForm.phone;
//       ElMessage.success('手机绑定成功');
//       bindPhoneDialogVisible.value = false;
//     } else {
//       return false;
//     }
//   });
// };

// 方法：显示注销账号对话框
// const showDeleteAccountDialog = () => {
//   deleteAccountForm.password = '';
//   deleteAccountForm.confirm = false;
//   deleteAccountDialogVisible.value = true;
// };

// 方法：注销账号
// const deleteAccount = () => {
//   deleteAccountFormRef.value.validate((valid) => {
//     if (valid) {
//       // 这里应该调用API注销账号
//       ElMessage.success('账号已注销');
//       deleteAccountDialogVisible.value = false;
//       // 注销后应该跳转到登录页
//       router.push('/login');
//     } else {
//       return false;
//     }
//   });
// };

// 组件挂载后的处理
onMounted(() => {
  // 这里可以加载用户数据
  // 例如：从API获取用户信息、学习记录、收藏内容等
  console.log('用户中心组件已挂载');
});
</script>

<style scoped>
.user-center-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'PingFang SC', 'Helvetica Neue', Helvetica, 'microsoft yahei', arial, STHeiTi, sans-serif;
}

.page-header {
  margin-bottom: 30px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 15px;
}

.page-header h1 {
  font-size: 28px;
  color: #303133;
  margin-bottom: 8px;
  font-weight: 600;
}

.page-header p {
  color: #606266;
  font-size: 16px;
  margin: 0;
}

.user-center-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.user-info {
  display: flex;
  align-items: center;
}

.user-details {
  margin-left: 20px;
}

.user-name {
  font-size: 20px;
  margin: 0 0 8px 0;
}

.user-bio {
  color: #666;
  margin: 0;
  max-width: 400px;
}

.user-stats {
  display: flex;
  gap: 30px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.stat-label {
  color: #666;
  font-size: 14px;
}

.user-center-content {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;
  margin-bottom: 30px;
}

.user-tabs {
  width: 100%;
}

.user-tabs :deep(.el-tabs__header) {
  margin-bottom: 20px;
}

.user-tabs :deep(.el-tabs__item) {
  font-size: 16px;
  padding: 0 20px;
}

.sub-tabs {
  margin-top: 20px;
}

/* 学习记录卡片样式 */
.record-card, .course-card, .discussion-card, .question-card, .note-card {
  margin-bottom: 20px;
  transition: all 0.3s;
}

.record-card:hover, .course-card:hover, .discussion-card:hover, .question-card:hover, .note-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.record-content, .course-content, .discussion-content, .question-content, .note-content {
  display: flex;
  margin-bottom: 15px;
}

.record-image, .course-image {
  width: 120px;
  height: 80px;
  overflow: hidden;
  border-radius: 4px;
  margin-right: 15px;
  flex-shrink: 0;
}

.record-image img, .course-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.record-info, .course-info {
  flex: 1;
}

.record-title, .course-title, .discussion-title, .question-title, .note-title {
  margin: 0 0 10px 0;
  font-size: 16px;
  cursor: pointer;
  color: #303133;
}

.record-title:hover, .course-title:hover, .discussion-title:hover, .question-title:hover, .note-title:hover {
  color: #409EFF;
}

.record-progress {
  margin-bottom: 10px;
}

.record-meta, .course-meta, .discussion-meta, .question-meta, .note-meta {
  display: flex;
  color: #909399;
  font-size: 13px;
}

.record-meta span, .course-meta span, .discussion-meta span, .question-meta span, .note-meta span {
  margin-right: 15px;
}

.record-actions, .course-actions, .discussion-actions, .question-actions, .note-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 订单表格样式 */
.order-course {
  display: flex;
  align-items: center;
}

.order-course .course-image {
  width: 60px;
  height: 40px;
  margin-right: 10px;
}

.order-course .course-name {
  font-size: 14px;
}

/* 用户表单样式 */
.user-form {
  max-width: 600px;
  margin: 0 auto;
}

.avatar-uploader {
  width: 100px;
  height: 100px;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar-uploader:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.security-settings {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

/* 对话框样式 */
.warning-message {
  margin-bottom: 20px;
}

/* 空数据样式 */
.empty-data {
  padding: 30px 0;
}

/* 讨论、问题、笔记内容样式 */
.discussion-excerpt, .question-excerpt, .note-excerpt {
  color: #606266;
  margin: 10px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.discussion-stats, .question-stats, .note-stats {
  display: flex;
  margin-left: auto;
}

.discussion-stats span, .question-stats span, .note-stats span {
  display: flex;
  align-items: center;
  margin-left: 15px;
}

.discussion-stats .el-icon, .question-stats .el-icon, .note-stats .el-icon {
  margin-right: 5px;
}

/* 收藏课程价格样式 */
.course-price {
  margin-top: 10px;
}

.current-price {
  color: #f56c6c;
  font-weight: bold;
  font-size: 16px;
  margin-right: 10px;
}

.original-price {
  color: #909399;
  text-decoration: line-through;
  font-size: 14px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .user-center-container {
    padding: 15px;
  }
  
  .page-header h1 {
    font-size: 24px;
  }
  
  .page-header p {
    font-size: 14px;
  }
  
  .user-center-header {
    flex-direction: column;
    align-items: flex-start;
    padding: 15px;
  }
  
  .user-stats {
    margin-top: 20px;
    width: 100%;
    justify-content: space-around;
  }
  
  .record-content, .course-content {
    flex-direction: column;
  }
  
  .record-image, .course-image {
    width: 100%;
    height: 150px;
    margin-right: 0;
    margin-bottom: 15px;
  }
  
  .user-center-content {
    padding: 15px;
  }
  
  .user-tabs :deep(.el-tabs__item) {
    font-size: 14px;
    padding: 0 10px;
  }
}
</style>